<?php


namespace app\api\model;


use app\common\library\IDMan;
use app\common\library\PlatformModel;
use app\common\library\StatModel;
use app\common\model\BaseModel;
use common;
use ApiOper;
use think\facade\Log;

class UserChargeModel extends BaseModel
{
    protected $name = 'user_charge_order';
    protected $pk = 'id';

    protected $charge_list =[
        'default'=>[
            ['num' => 10,'score'=>0,'remark'=>'','coup'=>0],
            ['num' => 20,'score'=>0,'remark'=>'','coup'=>0],
            ['num' => 50,'score'=>0,'remark'=>'','coup'=>0]
        ],
        '450924' =>[
            ['num' => 10,'score'=>0,'remark'=>'送1元优惠卷','coup'=>1],
            ['num' => 20,'score'=>0,'remark'=>'送1元优惠卷*5','coup'=>5],
            ['num' => 50,'score'=>0,'remark'=>'送1元优惠卷*20','coup'=>20]
        ]
    ];

    function get_charge_list($city_id)
    {
        if (empty($city_id) || $city_id == null)
            return $this->charge_list['default'];

        if (isset($this->charge_list[$city_id]))
            return $this->charge_list[$city_id];
        else
            return $this->charge_list['default'];
    }

    function sumbit_alipay($city_id,$userinfo, $amount,$profit_sharing = false)
    {
        $alipay_user_id = $userinfo['alipay_user_id'];

        $pay_city = 'default';
        if (empty($pay_city)){
            $pay_city = 'default';
        }

        $is_profit = $profit_sharing ? 1:0;
        $order_id = IDMan::order_id();
        $ret = (new PayModel($pay_city))->alipay_create_trade($city_id, ORDER_TYPE_USER_CHARGE, $order_id, $alipay_user_id, $amount, '用户充值:' . ($amount / 100) . "元",$pay_city);
        if (!empty($ret)) {
            $order_info = [
                'id' => $order_id,
                'city_id' => $city_id,
                'amount' => $amount,
                'user_id' => $userinfo['id'],
                'user_name' => $userinfo['name'],
                'user_phone' => $userinfo['phone'],
                'create_time' => date('Y-m-d H:i:s'),
                'order_state' => USER_CHARGE_ORDER_STATE_SUBMIT,
                'gateway' => PAY_GATEWAY_ALIPAY,
                'pay_city' => $pay_city,
                'is_profit' => $is_profit
            ];

            self::create($order_info);
        }
        return $ret;
    }

    function sumbit_aliapp($city_id,$userinfo, $amount)
    {
        $pay_city = 'default';
        if (empty($pay_city)){
            $pay_city = 'default';
        }
        $order_id = IDMan::order_id();
        $ret = (new PayModel($pay_city))->alipay_create_trade_app($city_id, ORDER_TYPE_USER_CHARGE, $order_id, $amount, '用户充值:' . ($amount / 100) . "元",$pay_city);
        if (!empty($ret)) {
            $order_info = [
                'id' => $order_id,
                'city_id' => $city_id,
                'amount' => $amount,
                'user_id' => $userinfo['id'],
                'user_name' => $userinfo['name'],
                'user_phone' => $userinfo['phone'],
                'create_time' => date('Y-m-d H:i:s'),
                'order_state' => USER_CHARGE_ORDER_STATE_SUBMIT,
                'gateway' => PAY_GATEWAY_ALIPAY,
                'pay_city' => $pay_city,
            ];

            self::create($order_info);
        }
        return $ret;
    }

    function submit_wxmp($city_id, $userinfo, $amount,$profit_sharing = false)
    {
        $pay_city = 'default';
        if (empty($pay_city)){
            $pay_city = 'default';
        }

        $is_profit = $profit_sharing ? 1:0;

        $order_id = IDMan::order_id();
        $ret = (new PayModel($pay_city))->wxmp_unifield_order($city_id, ORDER_TYPE_USER_CHARGE, $order_id, $amount, '小程序充值',$pay_city);
        if (empty($ret)) {
            $this->throw_myexception(X_ERROR, "统一下单失败!");
        }


        $platform = (new PlatformModel())->get_platform_info('wxmpu');
        $prepay_info = [
            'appId' => $platform['appid'],
            'package' => 'prepay_id=' . $ret['prepay_id'],
            'nonceStr' => uniqid(),
            'timeStamp' => time(),
            'signType' => 'MD5',
            // 'partnerid' => $ret['mch_id'],
        ];

        $sign = (new PayModel($pay_city))->wx_sign($prepay_info);
        $prepay_info['sign'] = $sign;

        $order_info = [
            'id' => $order_id,
            'city_id' => $city_id,
            'amount' => $amount,
            'user_id' => $userinfo['id'],
            'user_name' => $userinfo['name'],
            'user_phone' => $userinfo['phone'],
            'create_time' => date('Y-m-d H:i:s'),
            'order_state' => USER_CHARGE_ORDER_STATE_SUBMIT,
            'gateway' => PAY_GATEWAY_WEIXIN,
            'pay_city' => $pay_city,
            'is_profit' => $is_profit
        ];

        self::create( $order_info);
        return $prepay_info;
    }

    function submit_wxapp($city_id, $userinfo,$amount)
    {
        $pay_city = 'default';
        if (empty($pay_city)){
            $pay_city = 'default';
        }
        $order_id = IDMan::order_id();
        $ret = (new PayModel($pay_city))->wxapp_unifield_order($city_id, ORDER_TYPE_USER_CHARGE, $order_id, $amount, 'APP充值',$pay_city);
        if (empty($ret)) {
            $this->throw_myexception(X_ERROR, "统一下单失败!");
        }

        $platform = (new PlatformModel())->get_platform_info('wxapp');

        $prepay_info = [
            'appid' => $platform['appid'],
            'package' => 'prepay_id=' . $ret['prepayid'],
            'noncestr' => uniqid(),
            'timestamp' => time(),
            'prepayid' => $ret['prepayid'],
            'partnerid' => $ret['partnerid'],
        ];


        $sign = (new PayModel($city_id))->wx_sign($prepay_info);
        $prepay_info['sign'] = $sign;
        $prepay_info['mch_id'] = $ret['mch_id'];

        $order_info = [
            'id' => $order_id,
            'city_id' => $city_id,
            'amount' => $amount,
            'user_id' => $userinfo['id'],
            'user_name' => $userinfo['name'],
            'user_phone' => $userinfo['phone'],
            'create_time' => date('Y-m-d H:i:s'),
            'order_state' => USER_CHARGE_ORDER_STATE_SUBMIT,
            'gateway' => PAY_GATEWAY_WEIXIN,
            'pay_city' => $pay_city,
        ];

        self::create($order_info);
        return $prepay_info;
    }

    function finish($order_id, $payment_info)
    {
        $order_info = $this->query_info($order_id);
        if (empty($order_info)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "查询订单失败!");
        }

        if ($order_info['order_state'] != USER_CHARGE_ORDER_STATE_SUBMIT) {
            $this->throw_myexception(ERROR_STATE_DISMATCH, "订单状态不匹配!");
        }

        //修改数据库玩家的余额
        (new UserModel())->incr_balance($order_info['user_id'], $order_info['amount']);

        $data = [
            'order_state' => USER_CHARGE_ORDER_STATE_FINISHED,
            'end_time' => date('Y-m-d H:i:s'),
            'payment_info' => $payment_info,
        ];

        $where = [
            'id' => $order_id,
        ];

        //更新订单数据
        self::update($data, $where);

        //redis 每日用户充值排行
        (new StatModel())->user_charge_order_amount_incr($order_info['city_id'], $order_info['amount']);
        (new StatNewModel())->user_charge_incr($order_info['city_id'], $order_info['amount'], date('Y-m-d'));

        //添加积分
        $list = $this->charge_list['default'];
        if ($order_info['city_id']&&isset($this->charge_list[$order_info['city_id']]))
        {
            $list = $this->charge_list[$order_info['city_id']];
        }

        if (!empty($list))
        {
            foreach ($list as $info){
                if ($order_info['amount'] == $info['num']*100){
                    if ($info['score'] > 0)
                    {
                        $city_info = (new CityModel())->query_info($order_info['city_id']);
                        if (!empty($city_info)){
                            $use_score = $city_info['score_rule']['use_score'];
                            if ($use_score != 0){
                                (new UserModel())->incr_score($order_info['user_id'], $info['score']);
                                //记录一下
                                $user_data=[
                                    'id' => $order_info['user_id'],
                                    'name' => $order_info['user_name'],
                                    'phone' => $order_info['user_phone']
                                ];
                                (new ExchangeModel())->record($order_info['city_id'],$user_data,SCORE_GATEWAY_CHAREGE,$info['score']);
                            }
                        }
                    }

                    //赠送优惠卷
                    if (isset($info['coup'])&&$info['coup']>0){
                        $coup = $info['coup'];

                        $duration = 365*3600*24;
                        for ($i = 0; $i < $coup;++$i){
                            (new CouponModel())->coupon_for_type_1($order_info['user_id'],100,$duration,'充值赠送');
                        }
                    }
                    break;
                }
            }
        }


        //分账
        if ($order_info['is_profit'] == 1 &&  $order_info['amount'] > 0) {

            $trans_id = null;
            if ($order_info['gateway'] == PAY_GATEWAY_WEIXIN){
                $trans_id = $payment_info['transaction_id'];
            }
            else if ($order_info['gateway'] == PAY_GATEWAY_ALIPAY){
                $trans_id = $payment_info['trade_no'];
            }
            if (!empty($trans_id)){
                //分账
                (new PayModel())->timer_profitshare($order_info['city_id'],$order_info['amount'],$trans_id,ORDER_TYPE_USER_CHARGE,$order_info['gateway'],$order_info['id']);
            }

        }
    }

    function query_info($order_id)
    {
        $selectlist = [
            'city_id' => 'string',
            'id' => 'string',
            'user_id' => 'string',
            'user_name' => 'string',
            'user_phone' => 'string',
            'gateway' => 'string',
            'amount' => 'int',
            'refund_amount' => 'int',
            'order_state' => 'int',
            'create_time' => 'string',
            // 'payment_info' => 'array',
            'end_time' => 'string',
            'refund_order_id' => 'string',
            'refund_amount_total' => 'int',
            'pay_city' => 'string',
            'is_profit' => 'int',
        ];


        $sfs = common::array_keys($selectlist);
        $beans = [
            'id'=>$order_id,
        ];

        $info = $this->where($beans)->field($sfs)->find();
        return $info;
    }

    function query_list($cd, $pos, $limit)
    {
        $selectlist = [
            'id' => 'string',
            'user_id' => 'string',
            'user_name' => 'string',
            'user_phone' => 'string',
            'gateway' => 'string',
            'amount' => 'int',
            'order_state' => 'int',
            'create_time' => 'string',
            'payment_info' => 'array',
            'end_time' => 'string',
            'oper_id' => 'string',
            'oper_name' => 'string',
            'refund_amount' => 'int',
            'refund_amount_total' => 'int',
            'refund_order_id' => 'string',
            'is_profit' => 'int',
        ];

        $sfs = common::array_keys($selectlist);
        $beans = [
        ];
        if (isset($cd['user_id'])) {
            $beans['user_id'] = $cd['user_id'];
        }

        if (isset($cd['oper_id'])) {
            $beans['oper_id'] = $cd['oper_id'];
        }
        if (isset($cd['order_state'])) {
            $beans['order_state'] = $cd['order_state'];
           // hisql::bound_arg('order_state', $cd['order_state'], $st, $beans);
        }
        if (isset($cd['refundable'])) {
            //$st = $st . " and (gateway = ? or gateway = ?)";
            $beans['gateway'] = [PAY_GATEWAY_WEIXIN,PAY_GATEWAY_ALIPAY,'or'];
        }

        $rows =$this->where($beans)->field($sfs)->order('create_time','desc')->limit($pos,$limit)->select();
        return $rows->toArray();
    }

    function add_refund_record($city_id, $amount, $userinfo, $reason_type, $reason_desc, $reason_imgs)
    {
        $order_id = IDMan::city_order_id($city_id);
        $pay_id = IDMan::city_order_id($city_id);

        $payment_info = [
            'pay_id' => $pay_id,
            'reason_type' => $reason_type,
            'reason_desc' => $reason_desc,
            'reason_imgs' => $reason_imgs,
        ];

        $pay_city = 'default';

        $order_info = [
            'id' => $order_id,
            'city_id' => $city_id,
            'amount' => 0 - $amount,
            'user_id' => $userinfo['id'],
            'user_name' => $userinfo['name'],
            'user_phone' => $userinfo['phone'],
            'create_time' => date('Y-m-d H:i:s'),
            'order_state' => USER_CHARGE_ORDER_STATE_FINISHED,
            'gateway' => PAY_GATEWAY_OFFLINE,
            'end_time' => date('Y-m-d H:i:s'),
            'payment_info' => $payment_info,
            'oper_id' => ApiOper::instance()->userinfo()['id'],
            'oper_name' => ApiOper::instance()->userinfo()['name'],
            'pay_city' =>$pay_city,
        ];

        hisql::insert('tb_user_charge_order', $order_info);


        (new StatModel())->user_refund_order_amount_incr($order_info['city_id'], $order_info['amount']);
        (new PayModel)->add_record($city_id, $userinfo['id'], ORDER_TYPE_USER_CHARGE_REFUND, $order_id, PAY_GATEWAY_OFFLINE, 0 - $amount);
        return $order_info;
    }

    function submit_refund($order_id, $amount, $reason)
    {
        $order_info = $this->query_info($order_id);
        if (empty($order_info)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "查询订单信息失败！");
        }

        if ($order_info['order_state'] != USER_CHARGE_ORDER_STATE_FINISHED) {
            $this->throw_myexception(ERROR_QUERY_INFO, "未完成支付订单！");
        }

        $pay_city = 'default';
        if (!empty($order_info['pay_city'])){
            $pay_city = $order_info['pay_city'];
        }

        $ret = (new PayModel($pay_city))->submit_refund($order_info['id'], ORDER_TYPE_USER_CHARGE_REFUND, $amount, $reason,$order_info['is_profit']);

        $order_state = USER_CHARGE_ORDER_STATE_REFUND;
        $refund_total = $order_info['refund_amount_total'] + $amount;
        if ($ret->order_state == PAY_ORDER_STATE_REFUND_FINISH) {
            $order_state = $refund_total >= $order_info['amount'] ? USER_CHARGE_ORDER_STATE_REFUND_FINISH : USER_CHARGE_ORDER_STATE_FINISHED;
        }

        $data = [
            'order_state' => $order_state,
            'refund_order_id' => $ret->order_id,
            'refund_amount' => $amount,
            'refund_amount_total' => $refund_total,
            'refund_amount' => $amount,
        ];
        if ($ret->order_state == PAY_ORDER_STATE_REFUND_FINISH) {
            $data['order_state'] = $refund_total >= $amount ? USER_CHARGE_ORDER_STATE_REFUND_FINISH : USER_CHARGE_ORDER_STATE_FINISHED;
            $data['payment_info'] = $ret;
            $data['end_time'] = date('Y-m-d H:i:s');
        }

        $where = [
            'id' => $order_id,
        ];

        self::update($data, $where);
        (new UserModel())->incr_balance($order_info['user_id'], 0 - $amount);
        (new StatNewModel())->user_charge_refund($order_info['city_id'], $amount, date('Y-m-d'));

        $userinfo = (new UserModel())->query_info($order_info['user_id']);
        $log = "用户充值退款：{$userinfo['name']}, {$userinfo['phone']} 发起退款，订单id：{$order_id}, 金额:{$amount}";
        Log::debug($log);
    }

    function refund_finish($order_id, $payment_info)
    {
        $order_info = $this->query_info($order_id);
        if (empty($order_info)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "查询订单失败!");
        }

        if ($order_info['order_state'] != USER_CHARGE_ORDER_STATE_REFUND) {
            $this->throw_myexception(ERROR_STATE_DISMATCH, "订单状态不匹配!");
        }

        $order_state = $order_info['refund_amount_total'] >= $order_info['amount'] ? USER_CHARGE_ORDER_STATE_REFUND_FINISH : USER_CHARGE_ORDER_STATE_FINISHED;
        $data = [
            'order_state' => $order_state,
            'end_time' => date('Y-m-d H:i:s'),
        ];
        if ($payment_info) {
            $data['payment_info'] = $payment_info;
        }

        $where = [
            'id' => $order_id,
        ];

        self::update( $data, $where);
    }

    function present_to($city_id, $userinfo, $amount, $remark)
    {
        $order_id = IDMan::order_id();
        $order_info = [
            'id' => $order_id,
            'city_id' => $city_id,
            'amount' => $amount,
            'user_id' => $userinfo['id'],
            'user_name' => $userinfo['name'],
            'user_phone' => $userinfo['phone'],
            'create_time' => date('Y-m-d H:i:s'),
            'order_state' => USER_CHARGE_ORDER_STATE_FINISHED,
            'gateway' => PAY_GATEWAY_PRESENT,
        ];

        self::create($order_info);

        $detail = [
            'oper' => ApiOper::instance()->userinfo()['name'],
            'remark' => $remark,
        ];
        (new PayModel)->add_record($city_id,
            $userinfo['id'],
            ORDER_TYPE_USER_CHARGE,
            $order_id,
            PAY_GATEWAY_PRESENT,
            $amount,
            $detail);

        (new UserModel())->incr_balance($order_info['user_id'], $order_info['amount']);
    }

    function submit_wxmp_profit($city_id, $userinfo, $amount)
    {
        $pay_city = 'default';
        if (empty($pay_city)){
            $pay_city = 'default';
        }
        $order_id = IDMan::order_id();
        $ret = (new PayModel($pay_city))->wxmp_unifield_order($city_id, ORDER_TYPE_USER_CHARGE, $order_id, $amount, '小程序充值',$pay_city,true);
        if (empty($ret)) {
            $this->throw_myexception(X_ERROR, "统一下单失败!");
        }


        $platform = (new PlatformModel())->get_platform_info('wxmpu');
        $prepay_info = [
            'appId' => $platform['appid'],
            'package' => 'prepay_id=' . $ret['prepay_id'],
            'nonceStr' => uniqid(),
            'timeStamp' => time(),
            'signType' => 'MD5',
            // 'partnerid' => $ret['mch_id'],
        ];

        $sign = (new PayModel($pay_city))->wx_sign($prepay_info);
        $prepay_info['sign'] = $sign;

        $order_info = [
            'id' => $order_id,
            'city_id' => $city_id,
            'amount' => $amount,
            'user_id' => $userinfo['id'],
            'user_name' => $userinfo['name'],
            'user_phone' => $userinfo['phone'],
            'create_time' => date('Y-m-d H:i:s'),
            'order_state' => USER_CHARGE_ORDER_STATE_SUBMIT,
            'gateway' => PAY_GATEWAY_WEIXIN,
            'pay_city' => $pay_city,
            'is_profit' => 1,
        ];

        self::create($order_info);
        return $prepay_info;
    }
}
